<script setup>
import {computed, reactive, ref} from "vue";
import {Delete, Plus} from "@element-plus/icons-vue";
import useUserInfoStore from "@/store/user.js";
import {ElMessage} from "element-plus";
import {GetUserInfo, UpdateUserDetail} from "@/api/index.js";
const store = useUserInfoStore();
const user_detail = reactive({
  age: "",
  sex: "",
  birthday: "",
  mobile: "",
  synopsis: "",
  position: "",
  email: "",
  address: ''
});
const ruleFormRef = ref();
// 校验数据
const rules = reactive({
  age: [{ required: true, message: "请输入年龄", trigger: "blur" }],
  sex: [{ required: true, message: "请选择性别", trigger: "change" }],
  birthday: [{ required: true, message: "请输入生日", trigger: "change" }],
  mobile: [{ required: true, message: "请输入联系方式", trigger: "change" }],
  synopsis: [{ required: true, message: "请输入简介", trigger: "change" }],
  email: [{ required: true, message: "请输入邮箱", trigger: "change" }],
  address: [{ required: true, message: "请输入联系地址", trigger: "change" }],
});

//用户头像
const uploadRef = ref()
const img_url = ref()
const checkfile = (file) => {//复制图片
  img_url.value = file.raw
}
const handleRemove = (file) => {// 删除选择的图片
  uploadRef.value.submit()
}

const SEX_TYPE = ["女", "男"];

const user_detail_copy= ref()
const handleRollBackUserDetail = ()=>{
  for (var i in user_detail){
    user_detail[i] = user_detail_copy.value[i]
  }
}
// 提交数据给后端 修改用户详情数据
const handleUpdateUserDetail =async ()=>{
  let formdata = new FormData()

  for (let i in user_detail){
    formdata.append(i,user_detail[i])
  }
  if(img_url.value){
    formdata.append('avatar',img_url.value)
  }
  try {
    const res = await UpdateUserDetail(formdata)
    console.log(res);
    if(res.status===200){
      store.SetUserAvatar(res.avatar)
      ElMessage.success(res.msg)
      await handleGetUserInfo()//重新获取用户数据
    }else{
      ElMessage.error(res.msg)
      handleRollBackUserDetail()
    }
  } catch (error) {
    console.log(error);
    handleRollBackUserDetail()
  }
}
const submitForm = (formEl) => {
  if (!formEl) return
  formEl.validate((valid, fields) => {
    if (valid) {
      handleUpdateUserDetail()
    }
  })
}

// 获取用户数据
const handleGetUserInfo = async()=>{
  try {
    const {status,data} = await GetUserInfo()
    for (var i in user_detail){
      user_detail[i] = data.userdetail[i]
    }
    user_detail.email = data.email
    user_detail_copy.value = JSON.parse(JSON.stringify(user_detail))
  } catch (error) {
    console.log(error);
  }
}
handleGetUserInfo()

//职位
const position_show = computed(()=>{
  return JSON.parse(localStorage.getItem('userInfo'))['userInfo']['status']===18;
})

</script>

<template>
  <div class="userdetail">
    <div class="userdetail-box">
      <h2 class="title">用户详情信息</h2>
      <div class="centent">
        <el-form label-width="100px" :model="user_detail" style="max-width: 560px" ref="ruleFormRef" :rules="rules">
          <el-form-item label="用户头像">
            <el-upload ref="uploadRef" list-type="picture-card" :auto-upload="false" :limit="1" :multiple='false'
                       :on-change='checkfile'>
              <el-icon>
                <Plus />
              </el-icon>
              <template #file="{ file }">
                <div>
                  <img class="el-upload-list__item-thumbnail" :src="file.url" alt=""  />
                  <span class="el-upload-list__item-actions">
                    <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                      <el-icon>
                        <Delete />
                      </el-icon>
                    </span>
                  </span>
                </div>
              </template>
            </el-upload>
          </el-form-item>

          <el-form-item label="性别：" prop="sex">
            <el-select v-model="user_detail.sex" class="m-2" placeholder="请选择性别">
              <el-option v-for="(item, index) in SEX_TYPE" :key="index" :label="item" :value="index" />
            </el-select>
          </el-form-item>

          <el-form-item label="年龄：" prop="age">
            <el-input v-model="user_detail.age" />
          </el-form-item>
          <el-form-item label="生日：" prop="birthday">
            <div class="block">
              <el-date-picker v-model="user_detail.birthday" type="date" placeholder="请选择日期" value-format="YYYY-MM-DD"/>
            </div>
          </el-form-item>
          <el-form-item label="手机号码：" prop="mobile">
            <el-input v-model="user_detail.mobile" type="text" />
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-input v-model="user_detail.email" type="text" />
          </el-form-item>

          <el-form-item label="职位" prop="position" v-if="position_show">
            <el-input v-model="user_detail.position" type="text" disabled />
          </el-form-item>


          <el-form-item label="地址" prop="address">
            <el-input v-model="user_detail.address" type="text" />
          </el-form-item>

          <el-form-item label="个人简介" prop="synopsis">
            <el-input v-model="user_detail.synopsis" :rows="3" type="textarea" placeholder="请输入个人简介" autocomplete="off" />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)">修改信息</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<style scoped lang="less">
.userdetail-box {
  width: 700px;
  padding-bottom: 20px;
  background: #fff;
  margin: auto;
  box-shadow: 0 0 12px rgba(0, 0, 0, 0.12);
  border-radius: 15px;

  .title {
    text-align: center;
    padding: 20px;
  }

  .centent {
    width: 560px;
    margin: auto;

    .el-form {
      .el-form-item {
        margin-top: 30px;
      }
    }

    .el-button {
      width: 300px;
      margin-left: 10px;
    }
  }
}
</style>